package com.jlgle.test;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.IniFactorySupport;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class Md5PasswordRealm extends SimpleAccountRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		if (StringUtils.isEmpty(username)) {
			throw new AccountException("未知的账号异常");
		}

		Object credentials = token.getCredentials();
		String pass = DigestUtils.md5Hex(new String((char[]) credentials));

		Ini ini = IniFactorySupport.loadDefaultClassPathIni();
		String password = ini.getSectionProperty("users", username);
		if (!StringUtils.equalsIgnoreCase(pass, password)) {
			throw new CredentialsException("密码不正确");
		}
		return new SimpleAuthenticationInfo(username, credentials, getName());
	}

}
